import { Component, OnInit, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { UploadFile } from 'ng-zorro-antd';
import { NotifyService } from 'abp-ng2-module/dist/src/notify/notify.service';
import { AppConsts } from '@shared/AppConsts';

@Component({
    moduleId: module.id,
    selector: 'upload-image',
    templateUrl: 'upload-image.component.html',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => UploadImageComponent),
            multi: true
        }
    ]
})
export class UploadImageComponent implements ControlValueAccessor, OnInit {
    @Input() maxLength = 5;
    @Input() folder: string = 'default';

    imagePaths: string;
    baseUrl = AppConsts.remoteServiceBaseUrl;

    previewImage = '';
    previewVisible = false;
    postUrl: string = '/File/FilesPosts?folder=';
    imageList: UploadFile[] = [];

    onChangeListener: any = () => { }; // 改变值回调
    onTouchedListener: any = () => { }; // 交互回调
    isDisabled: boolean;
    constructor(private notify: NotifyService) {

    }

    writeValue(obj: string): void {
        if (obj) {
            let paths = obj.split(',');
            paths.forEach((path) => {
                let fuid = path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
                let fname = path.substring(path.lastIndexOf('/') + 1);
                let furl = this.baseUrl + path;
                let file: any = { uid: fuid, name: fname, status: 'done', url: furl };
                this.imageList.push(file);
            });
            console.log(obj);
            console.table(this.imageList);
        }
        this.imagePaths = obj;
    }

    registerOnChange(fn: any): void {
        this.onChangeListener = fn; // 保存这个函数
    }

    registerOnTouched(fn: any): void {
        this.onTouchedListener = fn; // 保存这个函数
    }

    setDisabledState?(isDisabled: boolean): void {
        this.isDisabled = isDisabled;
    }

    ngOnInit(): void {
        this.postUrl = this.postUrl + this.folder
    }

    /**
         * 图片查看
         * @param file 
         */
    handlePreview = (file: UploadFile) => {
        this.previewImage = file.url || file.thumbUrl;
        this.previewVisible = true;
    }

    handleChange = (info: { file: UploadFile }): void => {
        if (info.file.status === 'error') {
            this.notify.error('上传图片异常，请重试', '');
            this.previewVisible = false;
        }
        if (info.file.status === 'done') {
            //this.notify.success('上传文件成功');
            var res = info.file.response.result;
            this.imagePaths = '';
            this.imageList.map(img => {
                if (img.uid == info.file.uid) {
                    img.url = this.baseUrl + res;
                }
                this.imagePaths = this.imagePaths + img.url.replace(this.baseUrl, '') + ','//拼接URL
                return img;
            })
            //console.log(this.imagePaths);
            if (this.onChangeListener) {
                this.onChangeListener(this.imagePaths); // 告诉form，你的表单值改变成了
            }
        }
    }

}
